<template>
  <div class="LineChart" :style="{height:height,width:width}">
    <slot name='nodata'></slot>
    <div :class="className" :style="{height:height,width:width}"></div>
  </div>
</template>
<script>
import echarts from 'echarts'; // echarts theme
import { debounce } from '@/util/util';
require('echarts/theme/macarons');
export default {
  name: 'LineChart',
  props: {
    className: {
      type: String,
      default: 'chart'
    },
    width: {
      type: String,
      default: '100%'
    },
    height: {
      type: String,
      default: '450px'
    },
    typeLine: {
      type: String
    },
    autoResize: {
      type: Boolean,
      default: true
    }
  },
  data () {
    return {
      chart: null
    };
  },
  mounted () {
    this.$BUS.$on('line.chart', (data) => {
      this.initChart(data);
    });
    if (this.autoResize) {
      this.__resizeHanlder = debounce(() => {
        if (this.chart) {
          this.chart.resize();
        }
      }, 100);
      window.addEventListener('resize', this.__resizeHanlder);
    }

    // 监听侧边栏的变化
    const sidebarElm = document.getElementsByClassName('_sidebar')[0];
    sidebarElm.addEventListener('transitionend', this.__resizeHanlder);
  },
  beforeDestroy () {
    this.dispose();
  },
  methods: {
    dispose () {
      if (!this.chart) {
        return;
      }
      if (this.autoResize) {
        window.removeEventListener('resize', this.__resizeHanlder);
      }
      const sidebarElm = document.getElementsByClassName('_sidebar')[0];
      sidebarElm.removeEventListener('transitionend', this.__resizeHanlder);
      this.chart.dispose();
      this.chart = null;
    },
    setOptions (options) {
      this.chart.setOption(options, true);
    },
    initChart (val) {
      this.chart = echarts.init(this.$el, 'macarons');
      this.setOptions(val);
    }
  }
};
</script>
